use crate::collector::*;
use crate::prometheus::*;
use crate::tracing::*;
use crate::jaeger::*;
use crate::manager::*;
use crate::logging::*;
use crate::monitoring::*;
use std::sync::Arc;
use std::collections::HashMap;
use tokio::time::{sleep, Duration};

#[tokio::test]
async fn test_memory_metrics_collector() {
    let collector = Arc::new(MemoryMetricsCollector::new());
    
    // 注册一个计数器
    collector.register_metric("test_counter", "Test counter metric", MetricType::Counter, HashMap::new()).await.unwrap();
    
    // 增加计数器值
    collector.record_counter("test_counter", 5.0, HashMap::new()).await.unwrap();
    collector.record_counter("test_counter", 3.0, HashMap::new()).await.unwrap();
    
    // 获取指标
    let metrics = collector.gather().await.unwrap();
    assert_eq!(metrics.len(), 1);
    
    let counter_family = &metrics[0];
    assert_eq!(counter_family.name, "test_counter");
    assert_eq!(counter_family.metric_type, MetricType::Counter);
    assert_eq!(counter_family.metrics.len(), 1);
    
    if let MetricValue::Counter(value) = counter_family.metrics[0].value {
        assert_eq!(value, 8.0);
    } else {
        panic!("Expected counter value");
    }
}

#[tokio::test]
async fn test_gauge_operations() {
    let collector = Arc::new(MemoryMetricsCollector::new());
    
    // 注册一个仪表盘
    collector.register_metric("test_gauge", "Test gauge metric", MetricType::Gauge, HashMap::new()).await.unwrap();
    
    // 设置仪表盘值
    collector.set_gauge("test_gauge", 10.0, HashMap::new()).await.unwrap();
    
    // 增加仪表盘值
    collector.inc_gauge("test_gauge", 5.0, HashMap::new()).await.unwrap();
    
    // 减少仪表盘值
    collector.dec_gauge("test_gauge", 3.0, HashMap::new()).await.unwrap();
    
    let metrics = collector.gather().await.unwrap();
    let gauge_family = &metrics[0];
    
    if let MetricValue::Gauge(value) = gauge_family.metrics[0].value {
        assert_eq!(value, 12.0);
    } else {
        panic!("Expected gauge value");
    }
}

#[tokio::test]
async fn test_histogram_observations() {
    let collector = Arc::new(MemoryMetricsCollector::new());
    
    // 注册一个直方图
    collector.register_metric("test_histogram", "Test histogram metric", MetricType::Histogram, HashMap::new()).await.unwrap();
    
    // 观察一些值
    collector.observe_histogram("test_histogram", 0.1, HashMap::new()).await.unwrap();
    collector.observe_histogram("test_histogram", 0.5, HashMap::new()).await.unwrap();
    collector.observe_histogram("test_histogram", 1.5, HashMap::new()).await.unwrap();
    
    let metrics = collector.gather().await.unwrap();
    let histogram_family = &metrics[0];
    
    if let MetricValue::Histogram { count, sum, buckets } = &histogram_family.metrics[0].value {
        assert_eq!(*count, 3);
        assert_eq!(*sum, 2.1);
        assert!(buckets.len() > 0);
    } else {
        panic!("Expected histogram value");
    }
}

#[tokio::test]
async fn test_metrics_with_labels() {
    let collector = Arc::new(MemoryMetricsCollector::new());
    
    // 注册计数器
    collector.register_metric("labeled_counter", "Counter with labels", MetricType::Counter, HashMap::new()).await.unwrap();
    
    // 创建不同的标签
    let mut labels1 = HashMap::new();
    labels1.insert("method".to_string(), "GET".to_string());
    labels1.insert("status".to_string(), "200".to_string());
    
    let mut labels2 = HashMap::new();
    labels2.insert("method".to_string(), "POST".to_string());
    labels2.insert("status".to_string(), "201".to_string());
    
    // 记录不同标签的指标
    collector.record_counter("labeled_counter", 10.0, labels1).await.unwrap();
    collector.record_counter("labeled_counter", 5.0, labels2).await.unwrap();
    
    let metrics = collector.gather().await.unwrap();
    let counter_family = &metrics[0];
    
    // 应该有两个不同的指标实例
    assert_eq!(counter_family.metrics.len(), 2);
}

#[tokio::test]
async fn test_prometheus_exporter() {
    let collector = Arc::new(MemoryMetricsCollector::new());
    let exporter = PrometheusExporter::new(collector.clone());
    
    // 注册一些指标
    collector.register_metric("http_requests_total", "Total HTTP requests", MetricType::Counter, HashMap::new()).await.unwrap();
    collector.register_metric("memory_usage_bytes", "Memory usage in bytes", MetricType::Gauge, HashMap::new()).await.unwrap();
    
    // 添加一些数据
    let mut labels = HashMap::new();
    labels.insert("method".to_string(), "GET".to_string());
    collector.record_counter("http_requests_total", 100.0, labels.clone()).await.unwrap();
    collector.set_gauge("memory_usage_bytes", 1024000.0, HashMap::new()).await.unwrap();
    
    // 导出Prometheus格式
    let prometheus_output = exporter.export().await.unwrap();
    
    // 验证输出包含预期的内容
    assert!(prometheus_output.contains("# HELP http_requests_total Total HTTP requests"));
    assert!(prometheus_output.contains("# TYPE http_requests_total counter"));
    assert!(prometheus_output.contains("http_requests_total{method=\"GET\"}"));
    assert!(prometheus_output.contains("memory_usage_bytes 1024000"));
}

#[tokio::test]
async fn test_metrics_builder() {
    let collector = Arc::new(MemoryMetricsCollector::new());
    let builder = MetricsBuilder::new(collector.clone());
    
    // 创建计数器
    let counter = builder.counter("build_counter", "Built counter").await.unwrap();
    counter.inc().await.unwrap();
    counter.inc_by(5.0).await.unwrap();
    
    // 创建仪表盘
    let gauge = builder.gauge("build_gauge", "Built gauge").await.unwrap();
    gauge.set(42.0).await.unwrap();
    
    // 创建直方图
    let histogram = builder.histogram("build_histogram", "Built histogram").await.unwrap();
    histogram.observe(1.5).await.unwrap();
    
    let metrics = collector.gather().await.unwrap();
    assert_eq!(metrics.len(), 3);
}

#[tokio::test]
async fn test_histogram_timing() {
    let collector = Arc::new(MemoryMetricsCollector::new());
    let builder = MetricsBuilder::new(collector.clone());
    let histogram = builder.histogram("operation_duration", "Operation duration").await.unwrap();
    
    // 测试计时功能
    let result = histogram.time(|| async {
        sleep(Duration::from_millis(10)).await;
        "completed"
    }).await.unwrap();
    
    assert_eq!(result, "completed");
    
    let metrics = collector.gather().await.unwrap();
    let histogram_family = &metrics[0];
    
    if let MetricValue::Histogram { count, .. } = &histogram_family.metrics[0].value {
        assert_eq!(*count, 1);
    }
}

#[tokio::test]
async fn test_summary_observations() {
    let collector = Arc::new(MemoryMetricsCollector::new());
    
    collector.register_metric("test_summary", "Test summary metric", MetricType::Summary, HashMap::new()).await.unwrap();
    
    // 观察一些值
    for value in [0.1, 0.2, 0.3, 0.4, 0.5] {
        collector.observe_summary("test_summary", value, HashMap::new()).await.unwrap();
    }
    
    let metrics = collector.gather().await.unwrap();
    let summary_family = &metrics[0];
    
    if let MetricValue::Summary { count, sum, quantiles } = &summary_family.metrics[0].value {
        assert_eq!(*count, 5);
        assert_eq!(*sum, 1.5);
        assert!(quantiles.len() > 0);
    } else {
        panic!("Expected summary value");
    }
}

#[tokio::test]
async fn test_collector_reset() {
    let collector = Arc::new(MemoryMetricsCollector::new());
    
    // 添加一些指标
    collector.register_metric("test_metric", "Test metric", MetricType::Counter, HashMap::new()).await.unwrap();
    collector.record_counter("test_metric", 10.0, HashMap::new()).await.unwrap();
    
    let metrics_before = collector.gather().await.unwrap();
    assert_eq!(metrics_before.len(), 1);
    
    // 重置收集器
    collector.reset().await.unwrap();
    
    let metrics_after = collector.gather().await.unwrap();
    assert_eq!(metrics_after.len(), 0);
}

#[tokio::test]
async fn test_prometheus_counter_vec() {
    let counter_vec = new_counter_vec("http_requests", "HTTP requests", &["method", "status"]);
    
    // 获取带标签的计数器
    let counter = counter_vec.with_label_values(&["GET", "200"]).await.unwrap();
    counter.inc().await.unwrap();
    counter.inc_by(5.0).await.unwrap();
    
    let value = counter.get().await;
    assert_eq!(value, 6.0);
    
    // 收集指标
    let families = counter_vec.collect().await.unwrap();
    assert_eq!(families.len(), 1);
    assert_eq!(families[0].metrics.len(), 1);
}

#[tokio::test]
async fn test_system_metrics_collector() {
    let system_collector = SystemMetricsCollector::new();
    
    // 收集系统指标
    system_collector.collect_process_metrics().await.unwrap();
    
    let families = system_collector.collect().await.unwrap();
    assert!(families.len() >= 3); // 应该至少有3个系统指标
    
    let descriptions = system_collector.describe();
    assert_eq!(descriptions.len(), 3);
}

// ============= 分布式追踪系统测试 =============

#[tokio::test]
async fn test_span_creation_and_lifecycle() {
    // 测试Span的创建和生命周期
    let root_span = Span::new_root("test_operation", "test_service");
    assert!(!root_span.trace_id.is_empty());
    assert!(!root_span.span_id.is_empty());
    assert!(root_span.parent_id.is_none());
    assert_eq!(root_span.operation_name, "test_operation");
    assert_eq!(root_span.service_name, "test_service");
    assert_eq!(root_span.kind, SpanKind::Internal);
    assert!(!root_span.is_finished());
    
    // 创建子Span
    let child_span = root_span.new_child("child_operation", "test_service");
    assert_eq!(child_span.trace_id, root_span.trace_id);
    assert_ne!(child_span.span_id, root_span.span_id);
    assert_eq!(child_span.parent_id, Some(root_span.span_id.clone()));
    
    // 完成Span
    let finished_span = child_span.finish();
    assert!(finished_span.is_finished());
    assert!(finished_span.end_time.is_some());
    assert!(finished_span.duration.is_some());
}

#[tokio::test]
async fn test_span_attributes_and_tags() {
    let mut span = Span::new_root("test_operation", "test_service");
    
    // 添加标签
    span.set_tag("http.method", "GET");
    span.set_tag("http.url", "/api/test");
    assert_eq!(span.attributes.tags.get("http.method"), Some(&"GET".to_string()));
    assert_eq!(span.attributes.tags.get("http.url"), Some(&"/api/test".to_string()));
    
    // 添加日志
    span.log("info", "操作开始");
    span.log_with_fields("debug", "详细信息", {
        let mut fields = HashMap::new();
        fields.insert("key1".to_string(), "value1".to_string());
        fields
    });
    assert_eq!(span.attributes.logs.len(), 2);
    assert_eq!(span.attributes.logs[0].level, "info");
    assert_eq!(span.attributes.logs[0].message, "操作开始");
    
    // 设置状态
    span.set_status(SpanStatus::Ok, Some("成功完成".to_string()));
    assert_eq!(span.attributes.status, SpanStatus::Ok);
    assert_eq!(span.attributes.status_message, Some("成功完成".to_string()));
    
    // 设置错误
    span.set_error("测试错误");
    assert_eq!(span.attributes.status, SpanStatus::Error);
    assert_eq!(span.attributes.tags.get("error"), Some(&"true".to_string()));
    assert_eq!(span.attributes.tags.get("error.message"), Some(&"测试错误".to_string()));
}

#[tokio::test]
async fn test_trace_creation_and_management() {
    let root_span = Span::new_root("root_operation", "test_service");
    let mut trace = Trace::new(root_span.clone());
    
    assert_eq!(trace.trace_id, root_span.trace_id);
    assert_eq!(trace.root_span_id, root_span.span_id);
    assert_eq!(trace.spans.len(), 1);
    
    // 添加子Span
    let child_span1 = root_span.new_child("child1", "test_service");
    let child_span2 = root_span.new_child("child2", "test_service");
    trace.add_span(child_span1.clone());
    trace.add_span(child_span2.clone());
    
    assert_eq!(trace.spans.len(), 3);
    
    // 获取根Span
    let retrieved_root = trace.get_root_span();
    assert!(retrieved_root.is_some());
    assert_eq!(retrieved_root.unwrap().span_id, root_span.span_id);
    
    // 获取子Span
    let children = trace.get_child_spans(&root_span.span_id);
    assert_eq!(children.len(), 2);
    
    // 完成Trace
    let finished_trace = trace.finish();
    assert!(finished_trace.end_time.is_some());
    assert!(finished_trace.duration.is_some());
}

#[tokio::test]
async fn test_in_memory_trace_exporter() {
    let exporter = Arc::new(InMemoryTraceExporter::new());
    
    // 创建测试Span
    let span1 = Span::new_root("operation1", "service1").finish();
    let span2 = Span::new_root("operation2", "service2").finish();
    
    // 导出Span
    exporter.export_spans(vec![span1.clone(), span2.clone()]).await.unwrap();
    
    // 验证导出的Span
    let exported_spans = exporter.get_spans().await;
    assert_eq!(exported_spans.len(), 2);
    assert_eq!(exported_spans[0].operation_name, "operation1");
    assert_eq!(exported_spans[1].operation_name, "operation2");
    
    // 创建并导出Trace
    let root_span = Span::new_root("trace_operation", "trace_service");
    let trace = Trace::new(root_span).finish();
    exporter.export_trace(trace.clone()).await.unwrap();
    
    // 验证导出的Trace
    let exported_traces = exporter.get_traces().await;
    assert_eq!(exported_traces.len(), 1);
    assert_eq!(exported_traces[0].service_name, "trace_service");
    
    // 清空并验证
    exporter.clear().await;
    assert_eq!(exporter.get_spans().await.len(), 0);
    assert_eq!(exporter.get_traces().await.len(), 0);
}

#[tokio::test]
async fn test_console_trace_exporter() {
    let exporter = ConsoleTraceExporter::new(false);
    
    let span = Span::new_root("console_test", "console_service").finish();
    
    // 这个测试主要验证不会panic，实际输出会打印到控制台
    let result = exporter.export_spans(vec![span]).await;
    assert!(result.is_ok());
    
    let root_span = Span::new_root("console_trace", "console_service");
    let trace = Trace::new(root_span).finish();
    let result = exporter.export_trace(trace).await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_tracing_processor() {
    let config = TracingConfig {
        batch_size: 2,
        batch_timeout_ms: 1000,
        max_queue_size: 100,
        sampling_enabled: false, // 禁用采样以确保所有Span都被处理
        sampling_rate: 1.0,
    };
    
    let exporter = Arc::new(InMemoryTraceExporter::new());
    let processor = TracingProcessor::new(config, exporter.clone());
    
    // 处理单个Span
    let span1 = Span::new_root("processor_test1", "processor_service").finish();
    processor.process_span(span1).await.unwrap();
    
    // 检查队列状态
    let (span_queue_size, _) = processor.get_queue_stats().await;
    assert_eq!(span_queue_size, 1);
    
    // 添加第二个Span触发批量导出
    let span2 = Span::new_root("processor_test2", "processor_service").finish();
    processor.process_span(span2).await.unwrap();
    
    // 等待批量导出
    sleep(Duration::from_millis(100)).await;
    
    // 验证Span已被导出
    let exported_spans = exporter.get_spans().await;
    assert_eq!(exported_spans.len(), 2);
    
    // 刷新处理器
    processor.flush().await.unwrap();
    processor.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_tracing_context() {
    // 测试默认上下文
    let context = TracingContext::new();
    assert!(context.trace_id.is_none());
    assert!(context.span_id.is_none());
    assert!(context.sampled);
    assert!(context.baggage.is_empty());
    
    // 从Span创建上下文
    let span = Span::new_root("context_test", "context_service");
    let context_from_span = TracingContext::from_span(&span);
    assert_eq!(context_from_span.trace_id, Some(span.trace_id.clone()));
    assert_eq!(context_from_span.span_id, Some(span.span_id.clone()));
    
    // 测试baggage
    let mut context = TracingContext::new();
    context.set_baggage("user_id", "12345");
    context.set_baggage("request_id", "req-abc");
    assert_eq!(context.get_baggage("user_id"), Some(&"12345".to_string()));
    assert_eq!(context.get_baggage("request_id"), Some(&"req-abc".to_string()));
    
    // 转换为HTTP头部
    let headers = context.to_http_headers();
    assert!(headers.contains_key("X-Baggage-user_id"));
    assert!(headers.contains_key("X-Baggage-request_id"));
    assert_eq!(headers.get("X-Sampled"), Some(&"1".to_string()));
    
    // 从HTTP头部创建上下文
    let mut http_headers = HashMap::new();
    http_headers.insert("X-Trace-ID".to_string(), "trace-123".to_string());
    http_headers.insert("X-Span-ID".to_string(), "span-456".to_string());
    http_headers.insert("X-Sampled".to_string(), "0".to_string());
    http_headers.insert("X-Baggage-tenant".to_string(), "tenant-1".to_string());
    
    let context_from_headers = TracingContext::from_http_headers(&http_headers);
    assert_eq!(context_from_headers.trace_id, Some("trace-123".to_string()));
    assert_eq!(context_from_headers.span_id, Some("span-456".to_string()));
    assert!(!context_from_headers.sampled);
    assert_eq!(context_from_headers.get_baggage("tenant"), Some(&"tenant-1".to_string()));
}

#[tokio::test]
async fn test_tracing_manager() {
    let config = TracingConfig::default();
    let exporter = Arc::new(InMemoryTraceExporter::new());
    let manager = TracingManager::new("test_service".to_string(), config, exporter.clone());
    
    // 开始根Span
    let root_span = manager.start_root_span("root_operation").await.unwrap();
    assert_eq!(root_span.service_name, "test_service");
    assert_eq!(root_span.operation_name, "root_operation");
    
    // 开始子Span
    let child_span = manager.start_child_span(&root_span, "child_operation").await.unwrap();
    assert_eq!(child_span.trace_id, root_span.trace_id);
    assert_eq!(child_span.parent_id, Some(root_span.span_id.clone()));
    
    // 更新Span属性
    manager.set_span_tag(&child_span.span_id, "test.key", "test.value").await.unwrap();
    manager.log_span(&child_span.span_id, "info", "测试日志").await.unwrap();
    
    // 获取统计信息
    let stats = manager.get_stats().await;
    assert_eq!(stats.active_spans_count, 2); // root + child
    assert_eq!(stats.active_traces_count, 1);
    
    // 完成Span
    manager.finish_span(&child_span.span_id).await.unwrap();
    manager.finish_span(&root_span.span_id).await.unwrap();
    
    // 完成Trace
    manager.finish_trace(&root_span.trace_id).await.unwrap();
    
    // 验证统计信息更新
    let final_stats = manager.get_stats().await;
    assert_eq!(final_stats.active_spans_count, 0);
    assert_eq!(final_stats.active_traces_count, 0);
    
    // 关闭管理器
    manager.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_traced_operations() {
    let config = TracingConfig::default();
    let exporter = Arc::new(InMemoryTraceExporter::new());
    let manager = TracingManager::new("test_service".to_string(), config, exporter.clone());
    
    // 测试异步操作追踪
    let result = manager.trace_async("async_operation", async {
        sleep(Duration::from_millis(10)).await;
        Ok::<String, rustcloud_core::ServiceError>("async_result".to_string())
    }).await;
    
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), "async_result");
    
    // 测试同步操作追踪
    let sync_result = manager.trace_sync("sync_operation", || {
        Ok::<String, rustcloud_core::ServiceError>("sync_result".to_string())
    }).await;
    
    assert!(sync_result.is_ok());
    assert_eq!(sync_result.unwrap(), "sync_result");
    
    // 刷新并验证导出
    manager.flush().await.unwrap();
    sleep(Duration::from_millis(100)).await;
    
    let exported_spans = exporter.get_spans().await;
    assert_eq!(exported_spans.len(), 2);
    
    manager.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_simple_tracer() {
    let config = TracingConfig::default();
    let exporter = Arc::new(InMemoryTraceExporter::new());
    let manager = Arc::new(TracingManager::new("simple_service".to_string(), config, exporter.clone()));
    let tracer = SimpleTracer::new(manager.clone());
    
    // 开始操作
    let span_id = tracer.start("simple_operation").await.unwrap();
    assert!(!span_id.is_empty());
    
    // 记录事件和属性
    tracer.event(&span_id, "操作开始").await.unwrap();
    tracer.attribute(&span_id, "operation.type", "test").await.unwrap();
    
    // 完成操作
    tracer.finish(&span_id).await.unwrap();
    
    // 验证
    manager.flush().await.unwrap();
    sleep(Duration::from_millis(100)).await;
    
    let exported_spans = exporter.get_spans().await;
    assert_eq!(exported_spans.len(), 1);
    assert_eq!(exported_spans[0].operation_name, "simple_operation");
    
    manager.shutdown().await.unwrap();
}

// ============= 日志聚合和结构化日志系统测试 =============

#[tokio::test]
async fn test_log_entry_creation() {
    let entry = LogEntry::new(
        LogLevel::Info,
        "测试日志消息".to_string(),
        "test_service".to_string(),
        "instance_1".to_string(),
    );
    
    assert_eq!(entry.level, LogLevel::Info);
    assert_eq!(entry.message, "测试日志消息");
    assert_eq!(entry.service_name, "test_service");
    assert_eq!(entry.instance_id, "instance_1");
    assert!(entry.timestamp > 0);
    assert!(entry.trace_id.is_none());
    assert!(entry.fields.is_empty());
    assert!(entry.tags.is_empty());
}

#[tokio::test]
async fn test_log_entry_with_trace_and_fields() {
    let mut fields = HashMap::new();
    fields.insert("user_id".to_string(), serde_json::Value::String("12345".to_string()));
    fields.insert("request_id".to_string(), serde_json::Value::String("req-abc".to_string()));
    
    let entry = LogEntry::new(
        LogLevel::Error,
        "操作失败".to_string(),
        "payment_service".to_string(),
        "instance_2".to_string(),
    )
    .with_trace("trace-123".to_string(), Some("span-456".to_string()))
    .with_field("user_id", serde_json::Value::String("12345".to_string()))
    .with_tag("environment", "production");
    
    assert_eq!(entry.trace_id, Some("trace-123".to_string()));
    assert_eq!(entry.span_id, Some("span-456".to_string()));
    assert_eq!(entry.fields.len(), 1);
    assert_eq!(entry.tags.len(), 1);
    assert_eq!(entry.tags.get("environment"), Some(&"production".to_string()));
}

#[tokio::test]
async fn test_log_level_ordering() {
    assert!(LogLevel::Trace < LogLevel::Debug);
    assert!(LogLevel::Debug < LogLevel::Info);
    assert!(LogLevel::Info < LogLevel::Warn);
    assert!(LogLevel::Warn < LogLevel::Error);
    assert!(LogLevel::Error < LogLevel::Fatal);
    
    // 测试字符串转换
    assert_eq!(LogLevel::from_str("info"), LogLevel::Info);
    assert_eq!(LogLevel::from_str("ERROR"), LogLevel::Error);
    assert_eq!(LogLevel::from_str("unknown"), LogLevel::Info);
    
    assert_eq!(LogLevel::Debug.to_string(), "DEBUG");
    assert_eq!(LogLevel::Warn.to_string(), "WARN");
}

#[tokio::test]
async fn test_log_filter() {
    let filter = LogFilter {
        min_level: LogLevel::Warn,
        service_filters: vec!["test_service".to_string()],
        tag_filters: {
            let mut tags = HashMap::new();
            tags.insert("env".to_string(), "prod".to_string());
            tags
        },
        field_filters: HashMap::new(),
    };
    
    // 创建测试日志条目
    let entry_pass = LogEntry::new(
        LogLevel::Error,
        "错误消息".to_string(),
        "test_service".to_string(),
        "instance_1".to_string(),
    ).with_tag("env", "prod");
    
    let entry_fail_level = LogEntry::new(
        LogLevel::Info,
        "信息消息".to_string(),
        "test_service".to_string(),
        "instance_1".to_string(),
    ).with_tag("env", "prod");
    
    let entry_fail_service = LogEntry::new(
        LogLevel::Error,
        "错误消息".to_string(),
        "other_service".to_string(),
        "instance_1".to_string(),
    ).with_tag("env", "prod");
    
    let entry_fail_tag = LogEntry::new(
        LogLevel::Error,
        "错误消息".to_string(),
        "test_service".to_string(),
        "instance_1".to_string(),
    ).with_tag("env", "dev");
    
    assert!(filter.matches(&entry_pass));
    assert!(!filter.matches(&entry_fail_level));
    assert!(!filter.matches(&entry_fail_service));
    assert!(!filter.matches(&entry_fail_tag));
}

#[tokio::test]
async fn test_in_memory_log_aggregator() {
    let aggregator = InMemoryLogAggregator::new(100);
    
    // 添加单个日志条目
    let entry1 = LogEntry::new(
        LogLevel::Info,
        "第一条消息".to_string(),
        "service1".to_string(),
        "instance1".to_string(),
    );
    aggregator.append(entry1).await.unwrap();
    
    // 批量添加日志条目
    let entries = vec![
        LogEntry::new(
            LogLevel::Warn,
            "警告消息".to_string(),
            "service1".to_string(),
            "instance1".to_string(),
        ),
        LogEntry::new(
            LogLevel::Error,
            "错误消息".to_string(),
            "service2".to_string(),
            "instance2".to_string(),
        ),
    ];
    aggregator.append_batch(entries).await.unwrap();
    
    // 查询所有日志
    let all_logs = aggregator.query(LogFilter::default(), None).await.unwrap();
    assert_eq!(all_logs.len(), 3);
    
    // 查询特定级别的日志
    let error_filter = LogFilter {
        min_level: LogLevel::Error,
        ..Default::default()
    };
    let error_logs = aggregator.query(error_filter, None).await.unwrap();
    assert_eq!(error_logs.len(), 1);
    assert_eq!(error_logs[0].level, LogLevel::Error);
    
    // 获取统计信息
    let stats = aggregator.get_stats().await.unwrap();
    assert_eq!(stats.total_entries, 3);
    assert_eq!(stats.info_count, 1);
    assert_eq!(stats.warn_count, 1);
    assert_eq!(stats.error_count, 1);
    assert_eq!(stats.service_counts.get("service1"), Some(&2));
    assert_eq!(stats.service_counts.get("service2"), Some(&1));
    
    // 清空日志
    aggregator.clear().await.unwrap();
    let cleared_logs = aggregator.query(LogFilter::default(), None).await.unwrap();
    assert_eq!(cleared_logs.len(), 0);
}

#[tokio::test]
async fn test_log_entry_formatting() {
    let entry = LogEntry::new(
        LogLevel::Info,
        "测试消息".to_string(),
        "test_service".to_string(),
        "instance_1".to_string(),
    )
    .with_trace("trace-123".to_string(), Some("span-456".to_string()))
    .with_field("user_id", serde_json::Value::String("12345".to_string()))
    .with_tag("env", "production");
    
    // 测试JSON序列化
    let json_str = entry.to_json().unwrap();
    assert!(json_str.contains("test_service"));
    assert!(json_str.contains("trace-123"));
    assert!(json_str.contains("user_id"));
    
    // 测试格式化字符串
    let formatted = entry.to_formatted_string();
    assert!(formatted.contains("[INFO]"));
    assert!(formatted.contains("test_service/instance_1"));
    assert!(formatted.contains("测试消息"));
    assert!(formatted.contains("[trace:trace-123]"));
}

#[tokio::test]
async fn test_console_log_exporter() {
    let exporter = ConsoleLogExporter::new(LogFormat::Text, true);
    
    let entries = vec![
        LogEntry::new(
            LogLevel::Info,
            "信息消息".to_string(),
            "test_service".to_string(),
            "instance_1".to_string(),
        ),
        LogEntry::new(
            LogLevel::Error,
            "错误消息".to_string(),
            "test_service".to_string(),
            "instance_1".to_string(),
        ),
    ];
    
    // 这个测试主要验证不会panic，实际输出会打印到控制台
    let result = exporter.export(entries).await;
    assert!(result.is_ok());
    
    let result = exporter.shutdown().await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_simple_logger() {
    let aggregator = Arc::new(InMemoryLogAggregator::new(1000));
    let manager = Arc::new(LogManager::new(
        aggregator.clone(),
        "simple_service".to_string(),
        "instance_1".to_string(),
        10,
    ));
    
    let logger = SimpleLogger::new(manager.clone());
    
    // 使用简单接口记录各级别日志
    logger.trace("跟踪消息").await.unwrap();
    logger.debug("调试消息").await.unwrap();
    logger.info("信息消息").await.unwrap();
    logger.warn("警告消息").await.unwrap();
    logger.error("错误消息").await.unwrap();
    logger.fatal("致命错误消息").await.unwrap();
    
    // 验证日志已记录
    let stats = manager.get_stats().await.unwrap();
    assert_eq!(stats.total_entries, 6);
    assert_eq!(stats.trace_count, 1);
    assert_eq!(stats.debug_count, 1);
    assert_eq!(stats.info_count, 1);
    assert_eq!(stats.warn_count, 1);
    assert_eq!(stats.error_count, 1);
    assert_eq!(stats.fatal_count, 1);
    
    manager.shutdown().await.unwrap();
}

// ============= 性能监控和告警系统测试 =============

#[tokio::test]
async fn test_performance_threshold() {
    let threshold = PerformanceThreshold {
        metric: PerformanceMetric::ResponseTime,
        warning_threshold: 100.0,
        error_threshold: 500.0,
        critical_threshold: 1000.0,
        window_seconds: 60,
        consecutive_violations: 2,
    };
    
    assert_eq!(threshold.metric, PerformanceMetric::ResponseTime);
    assert_eq!(threshold.warning_threshold, 100.0);
    assert_eq!(threshold.error_threshold, 500.0);
    assert_eq!(threshold.critical_threshold, 1000.0);
    assert_eq!(threshold.consecutive_violations, 2);
}

#[tokio::test]
async fn test_alert_event_creation() {
    let alert = AlertEvent::new(
        AlertLevel::Warning,
        "响应时间超过阈值".to_string(),
        "响应时间达到150ms，超过警告阈值100ms".to_string(),
        "web_service".to_string(),
        "instance_1".to_string(),
        PerformanceMetric::ResponseTime,
        150.0,
        100.0,
    )
    .with_label("environment", "production")
    .with_label("version", "1.0.0");
    
    assert_eq!(alert.level, AlertLevel::Warning);
    assert_eq!(alert.service_name, "web_service");
    assert_eq!(alert.metric, PerformanceMetric::ResponseTime);
    assert_eq!(alert.current_value, 150.0);
    assert_eq!(alert.threshold, 100.0);
    assert_eq!(alert.status, AlertStatus::Triggered);
    assert_eq!(alert.labels.len(), 2);
    assert_eq!(alert.labels.get("environment"), Some(&"production".to_string()));
    
    // 测试恢复状态
    let resolved_alert = alert.resolve();
    assert_eq!(resolved_alert.status, AlertStatus::Resolved);
}

#[tokio::test]
async fn test_performance_data_point() {
    let data_point = PerformanceDataPoint::new(
        PerformanceMetric::CpuUsage,
        75.5,
        "cpu_service".to_string(),
        "instance_2".to_string(),
    )
    .with_label("core", "0")
    .with_label("mode", "user");
    
    assert_eq!(data_point.metric, PerformanceMetric::CpuUsage);
    assert_eq!(data_point.value, 75.5);
    assert_eq!(data_point.service_name, "cpu_service");
    assert_eq!(data_point.instance_id, "instance_2");
    assert!(data_point.timestamp > 0);
    assert_eq!(data_point.labels.len(), 2);
}

#[tokio::test]
async fn test_performance_metric_strings() {
    assert_eq!(PerformanceMetric::ResponseTime.to_string(), "response_time_ms");
    assert_eq!(PerformanceMetric::CpuUsage.to_string(), "cpu_usage_percent");
    assert_eq!(PerformanceMetric::MemoryUsage.to_string(), "memory_usage_percent");
    assert_eq!(PerformanceMetric::ErrorRate.to_string(), "error_rate_percent");
    assert_eq!(PerformanceMetric::RequestRate.to_string(), "request_rate_per_second");
    assert_eq!(PerformanceMetric::ActiveConnections.to_string(), "active_connections");
    assert_eq!(PerformanceMetric::QueueLength.to_string(), "queue_length");
}

#[tokio::test]
async fn test_alert_level_ordering() {
    assert!(AlertLevel::Info < AlertLevel::Warning);
    assert!(AlertLevel::Warning < AlertLevel::Error);
    assert!(AlertLevel::Error < AlertLevel::Critical);
    
    assert_eq!(AlertLevel::Warning.to_string(), "WARNING");
    assert_eq!(AlertLevel::Critical.to_string(), "CRITICAL");
}

#[tokio::test]
async fn test_console_alert_handler() {
    let handler = ConsoleAlertHandler::new("console_handler".to_string(), true);
    
    let alert = AlertEvent::new(
        AlertLevel::Error,
        "内存使用率过高".to_string(),
        "内存使用率达刄95%，超过错误阈值90%".to_string(),
        "memory_service".to_string(),
        "instance_1".to_string(),
        PerformanceMetric::MemoryUsage,
        95.0,
        90.0,
    );
    
    // 这个测试主要验证不会panic，实际输出会打印到控制台
    let result = handler.handle_alert(alert).await;
    assert!(result.is_ok());
    assert_eq!(handler.name(), "console_handler");
}

#[tokio::test]
async fn test_log_alert_handler() {
    let aggregator = Arc::new(InMemoryLogAggregator::new(1000));
    let handler = LogAlertHandler::new("log_handler".to_string(), aggregator.clone());
    
    let alert = AlertEvent::new(
        AlertLevel::Critical,
        "响应时间超时".to_string(),
        "响应时间达到6000ms，超过致命阈值5000ms".to_string(),
        "api_service".to_string(),
        "instance_3".to_string(),
        PerformanceMetric::ResponseTime,
        6000.0,
        5000.0,
    )
    .with_label("endpoint", "/api/users")
    .with_label("method", "GET");
    
    let result = handler.handle_alert(alert).await;
    assert!(result.is_ok());
    assert_eq!(handler.name(), "log_handler");
    
    // 验证日志已记录
    let logs = aggregator.query(LogFilter::default(), None).await.unwrap();
    assert_eq!(logs.len(), 1);
    assert_eq!(logs[0].level, LogLevel::Fatal);
    assert!(logs[0].message.contains("响应时间超时"));
    assert!(logs[0].fields.contains_key("alert_id"));
    assert!(logs[0].fields.contains_key("current_value"));
    assert_eq!(logs[0].tags.get("endpoint"), Some(&"/api/users".to_string()));
}

#[tokio::test]
async fn test_performance_monitor() {
    let collector = Arc::new(MemoryMetricsCollector::new());
    let monitor = PerformanceMonitor::new(
        "test_service".to_string(),
        "instance_1".to_string(),
        collector,
        1000,
    );
    
    // 添加阈值
    let threshold = PerformanceThreshold {
        metric: PerformanceMetric::ResponseTime,
        warning_threshold: 100.0,
        error_threshold: 500.0,
        critical_threshold: 1000.0,
        window_seconds: 60,
        consecutive_violations: 1, // 设置为1次以便测试
    };
    monitor.add_threshold(threshold).await;
    
    // 添加控制台告警处理器
    let console_handler = Arc::new(ConsoleAlertHandler::new(
        "test_console".to_string(),
        false,
    ));
    monitor.add_alert_handler(console_handler).await;
    
    // 记录正常指标
    monitor.record_metric(
        PerformanceMetric::ResponseTime,
        50.0,
        HashMap::new(),
    ).await.unwrap();
    
    // 记录超过警告阈值的指标
    monitor.record_metric(
        PerformanceMetric::ResponseTime,
        150.0,
        HashMap::new(),
    ).await.unwrap();
    
    // 获取统计信息
    let stats = monitor.get_performance_stats().await;
    assert_eq!(stats.total_data_points, 2);
    assert!(stats.metric_stats.contains_key(&PerformanceMetric::ResponseTime));
    
    let response_time_stats = &stats.metric_stats[&PerformanceMetric::ResponseTime];
    assert_eq!(response_time_stats.count, 2);
    assert_eq!(response_time_stats.sum, 200.0);
    assert_eq!(response_time_stats.avg, 100.0);
    assert_eq!(response_time_stats.min, 50.0);
    assert_eq!(response_time_stats.max, 150.0);
}

#[tokio::test]
async fn test_health_check_monitor() {
    let collector = Arc::new(MemoryMetricsCollector::new());
    let performance_monitor = Arc::new(PerformanceMonitor::new(
        "health_service".to_string(),
        "instance_1".to_string(),
        collector,
        1000,
    ));
    
    let health_monitor = HealthCheckMonitor::new(
        "health_service".to_string(),
        "instance_1".to_string(),
        performance_monitor.clone(),
    );
    
    // 执行健康检查
    let health_status = health_monitor.check_health().await.unwrap();
    assert_eq!(health_status, HealthStatus::Healthy);
    
    // 验证响应时间指标已记录
    let stats = performance_monitor.get_performance_stats().await;
    assert!(stats.metric_stats.contains_key(&PerformanceMetric::ResponseTime));
    assert_eq!(stats.metric_stats[&PerformanceMetric::ResponseTime].count, 1);
}

#[tokio::test]
async fn test_health_status_strings() {
    assert_eq!(HealthStatus::Healthy.to_string(), "healthy");
    assert_eq!(HealthStatus::Unhealthy.to_string(), "unhealthy");
    assert_eq!(HealthStatus::Degraded.to_string(), "degraded");
}